<template>
  <div class="ai-chat-container">
    <div class="chat-messages" ref="messagesContainer">
      <!-- 默认欢迎消息 -->
      <div v-if="messages.length === 0" class="welcome-message">
        <div class="welcome-icon">
          <img :src="aiAvatar" alt="AI assistant" />
        </div>
        <h3>AI智能助手小团团</h3>
        <p>您好！我是您的AI助手，请问有什么我可以帮您的吗？</p>
        <div class="suggestion-chips">
          <van-tag 
            v-for="(suggestion, index) in suggestions" 
            :key="index"
            type="primary"
            plain
            size="medium"
            class="suggestion-chip"
            @click="handleSuggestion(suggestion)">
            {{ suggestion }}
          </van-tag>
        </div>
      </div>

      <div v-for="(message, index) in messages" :key="index" 
           :class="['message-wrapper', message.type === 'user' ? 'user-wrapper' : 'ai-wrapper']">
        <div class="avatar">
          <img :src="message.type === 'user' ? userAvatar : aiAvatar" alt="avatar">
        </div>
        <div class="message" :class="message.type === 'user' ? 'user-message' : 'ai-message'">
          <div class="message-content" v-html="message.content"></div>
        </div>
      </div>
      <div v-if="isThinking" class="thinking-wrapper">
        <div class="thinking-indicator">
          <van-loading type="spinner" size="20px" color="#1989fa">思考中...</van-loading>
        </div>
      </div>
    </div>
    
    <div class="input-area">
      <van-field
        v-model="inputMessage"
        type="textarea"
        rows="1"
        autosize
        placeholder="请输入您的问题..."
        @keyup.enter="sendMessage"
        class="message-input"
      />
      <div class="button-group">
        <van-button 
          type="primary" 
          @click="sendMessage" 
          :disabled="isThinking"
          class="send-button"
          icon="arrow-up"
        />
        <van-button 
          type="primary" 
          @click="showQuickQuestions = true"
          class="quick-button"
          icon="plus"
        />
      </div>
    </div>

    <!-- 快捷问题弹出层 -->
    <van-popup
      v-model:show="showQuickQuestions"
      position="bottom"
      round
      :style="{ height: '50%' }"
    >
      <div class="quick-questions">
        <div class="quick-questions-header">
          <h3>快捷问题</h3>
          <van-icon name="cross" @click="showQuickQuestions = false" />
        </div>
        <div class="quick-questions-content">
          <div class="question-category" v-for="(category, index) in hospitalQuestions" :key="index">
            <h4>{{ category.title }}</h4>
            <div class="question-list">
              <van-tag
                v-for="(question, qIndex) in category.questions"
                :key="qIndex"
                type="primary"
                plain
                size="medium"
                class="question-tag"
                @click="handleQuickQuestion(question)"
              >
                {{ question }}
              </van-tag>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { Field, Button, Loading, Tag, Popup, Icon } from 'vant'
import axios from 'axios'
import MarkdownIt from 'markdown-it'
import { v4 as uuidv4 } from 'uuid'

// 头像图片
const userAvatar = 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
const aiAvatar = 'https://img.icons8.com/fluency/96/computer.png'

const md = new MarkdownIt({
  breaks: true,
  linkify: true,
  typographer: true
})

const messages = ref([])
const inputMessage = ref('')
const isThinking = ref(false)
const messagesContainer = ref(null)
const sessionId = ref('')

// 建议问题列表
const suggestions = [
  '你能帮我做什么？',
  '介绍一下你自己',
  '今天天气怎么样？',
  '讲个笑话'
]

// 快捷问题弹出层控制
const showQuickQuestions = ref(false)

// 医院相关快捷问题
const hospitalQuestions = [
  {
    title: '挂号相关',
    questions: [
      '如何预约挂号？',
      '挂号费用是多少？',
      '可以取消挂号吗？',
      '专家号怎么预约？'
    ]
  },
  {
    title: '就医指南',
    questions: [
      '医院门诊时间是什么时候？',
      '医院地址在哪里？',
      '怎么查询检查报告？',
      '住院需要准备什么？'
    ]
  },
  {
    title: '医保相关',
    questions: [
      '医保报销比例是多少？',
      '异地医保可以使用吗？',
      '医保卡丢失怎么办？',
      '医保定点医院有哪些？'
    ]
  },
  {
    title: '其他服务',
    questions: [
      '医院有停车位吗？',
      '可以预约体检吗？',
      '怎么查询医生出诊信息？',
      '医院有食堂吗？'
    ]
  }
]

const handleSuggestion = (suggestion) => {
  inputMessage.value = suggestion
  sendMessage()
}

const handleQuickQuestion = (question) => {
  inputMessage.value = question
  showQuickQuestions.value = false
  sendMessage()
}

// 清理HTML标签的函数
const cleanHtmlTags = (text) => {
  return text.replace(/<\/?[^>]+(>|$)/g, '')
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isThinking.value) return
  
  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: inputMessage.value
  })
  
  const userMessage = inputMessage.value
  inputMessage.value = ''
  isThinking.value = true
  
  // 创建AI消息对象
  const aiMessage = {
    type: 'ai',
    content: ''
  }
  messages.value.push(aiMessage)
  
  try {
    const response = await fetch('http://123.56.90.127:8086/chat/hospital/ai/send', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        message: userMessage,
        sessionId: sessionId.value
      })
    })

    if (!response.ok) {
      throw new Error('Network response was not ok')
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let accumulatedContent = ''

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      const chunk = decoder.decode(value)
      // 清理HTML标签
      const cleanedChunk = cleanHtmlTags(chunk)
      accumulatedContent += cleanedChunk
      
      // 使用markdown渲染
      aiMessage.content = md.render(accumulatedContent)
      
      // 滚动到底部
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('Error:', error)
    // 直接修改最后一条AI消息，而不是添加新消息
    aiMessage.content = '抱歉，发生了错误，请稍后重试。'
  } finally {
    isThinking.value = false
  }
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const generateSessionId = () => {
  sessionId.value = uuidv4()
  console.log('Generated new session ID:', sessionId.value)
}

onMounted(() => {
  generateSessionId()
  scrollToBottom()
})
</script>

<style scoped>
.ai-chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  background-image: 
    radial-gradient(circle at 25px 25px, rgba(0, 0, 0, 0.2) 2%, transparent 0%),
    radial-gradient(circle at 75px 75px, rgba(0, 0, 0, 0.2) 2%, transparent 0%);
  background-size: 100px 100px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  margin-bottom: 16px;
}

.welcome-message {
  text-align: center;
  padding: 32px 16px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin: 20px auto;
  max-width: 80%;
}

.welcome-icon {
  width: 64px;
  height: 64px;
  margin: 0 auto 16px;
  background: #fff;
  border-radius: 50%;
  padding: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.welcome-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.welcome-message h3 {
  color: #333;
  margin-bottom: 8px;
  font-size: 18px;
}

.welcome-message p {
  color: #666;
  margin-bottom: 16px;
  font-size: 14px;
  line-height: 1.5;
}

.suggestion-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
  margin-top: 16px;
}

.suggestion-chip {
  cursor: pointer;
  transition: all 0.3s ease;
}

.suggestion-chip:hover {
  transform: translateY(-2px);
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 8px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-wrapper {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message {
  max-width: 70%;
  word-wrap: break-word;
  position: relative;
}

.user-message {
  background-color: #1989fa;
  color: white;
  border-radius: 12px 12px 0 12px;
  padding: 12px;
  margin-left: auto;
}

.ai-message {
  background-color: white;
  border-radius: 12px 12px 12px 0;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-right: auto;
}

.message-content {
  line-height: 1.5;
}

.message-content :deep(p) {
  margin: 0;
}

.message-content :deep(pre) {
  background-color: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  overflow-x: auto;
}

.message-content :deep(code) {
  background-color: #f5f5f5;
  padding: 2px 4px;
  border-radius: 4px;
}

.input-area {
  display: flex;
  gap: 8px;
  padding: 12px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  align-items: center;
}

.message-input {
  flex: 1;
  background-color: #f7f8fa;
  border-radius: 8px;
  padding: 8px 12px;
  border: none;
}

.message-input :deep(.van-field__control) {
  min-height: 36px;
  max-height: 120px;
  line-height: 1.5;
}

.button-group {
  display: flex;
  gap: 8px;
}

.send-button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1989fa;
  border: none;
  box-shadow: 0 2px 4px rgba(25, 137, 250, 0.2);
}

.send-button:disabled {
  background-color: #c8c9cc;
  box-shadow: none;
}

.quick-button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1989fa;
  border: none;
  box-shadow: 0 2px 4px rgba(25, 137, 250, 0.2);
}

.thinking-wrapper {
  display: flex;
  margin: 8px 0;
  padding-left: 48px; /* 头像宽度 + 间距 */
}

.thinking-indicator {
  background-color: #f2f3f5;
  padding: 8px 16px;
  border-radius: 12px;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 8px;
}

.quick-questions {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.quick-questions-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.quick-questions-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.quick-questions-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.question-category {
  margin-bottom: 20px;
}

.question-category h4 {
  margin: 0 0 12px 0;
  color: #666;
  font-size: 14px;
}

.question-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.question-tag {
  cursor: pointer;
  transition: all 0.3s ease;
}

.question-tag:hover {
  transform: translateY(-2px);
  background-color: #e6f7ff;
}
</style>